<script setup>
import { useRoute } from 'vue-router';
import { ref, onMounted } from 'vue';
import { getExamList } from '@/api/index';
import { formateDateTime } from '@/utils/formatetime';
import router from '@/router';
import { submitExam } from '@/api/index';
const route = useRoute();
const pathParams = route.params;
const pathId = ref(null);
pathId.value = pathParams.id;

const examStartTime = formateDateTime(new Date());

const paramData = ref({
  examStartTime: '',
  submitTime: '',
  deviceId: '',
  groupCode: '',
  groupId: '',
  groupName: '',
  examDuration: 0,
  questionNum: 0,
  questionList: []
});//提交时的数据
paramData.value.examStartTime = examStartTime;

const listData = ref([])
const typeMap = ref({
  0: '单选题',
  1: '多选题',
  2: '判断题'
})

const time = ref(1* 60 * 1000);
const num = ref(1);
const onChange = (e) => {
  num.value = e + 1
}

const loading = ref(true);
const getExamListData = async () => { 
  const resData = (await getExamList(pathId.value)).data;
  listData.value = resData.questionList;
  paramData.value.groupCode = resData.groupCode;
  paramData.value.groupId = resData.groupId;
  paramData.value.groupName = resData.groupName;
  paramData.value.questionList = listData.value;
  paramData.value.examDuration = resData.examDuration;
  paramData.value.questionNum = resData.questionNum;
  time.value = resData.examDuration * 60 * 1000;
  loading.value = false;
}

onMounted(() => { 
  getExamListData();
})

// 单选类点击事件
const selectOneItem = ($event, item, item2, index, i) => {
  Array.from($event.currentTarget.parentNode.children).forEach(obj => {
    obj.classList.remove('active');
  })
  item.answerOptions.forEach((obj, j) => { 
    if (j === i) {
      $event.currentTarget.classList.add('active');
      obj.choose = true;
      item.isAnswered = 1;
    } else {
      obj.choose = false;
    }
  })
}

// 多选类点击事件
const selectMultiItem = ($event, item, item2, index, i) => { 
  if ($event.currentTarget.classList.contains('active')) { 
    $event.currentTarget.classList.remove('active');
    item2.choose = false;
  } else {
    $event.currentTarget.classList.add('active');
    item2.choose = true;
  }
  if (!item.answerOptions.every(obj => obj['choose'] === false)) {
    item.isAnswered = 1;
  } else {
    item.isAnswered = 0;
  }
}

/**
 * 交卷
 */
const examSubmit = () => {
  const message = ref('');
  if (listData.value.filter(obj => obj.isAnswered === 1).length === listData.value.length) {
    message.value = '已完成所有题目，请点击确认按钮交卷！';
  } else {
    message.value = '还有题目未完成，确认交卷？';
  }
  showConfirmDialog({
    message: message.value,
  }).then(async() => {
    const submitTime = formateDateTime(new Date());
    paramData.value.submitTime = submitTime;
    const resId = (await submitExam(paramData.value)).data.id;
    router.push(`/exam/result/${resId}`);
  }).catch(() => {

  })
  
}

const onFinish = async() => { 
  showNotify({ type: 'danger', message: '已到考试结束时间！' });
  const resId =(await submitExam(paramData.value)).data.id;
  router.push(`/exam/result/${resId}`);
}

const swipeRef = ref(null);
const nextPage = () => { 
  swipeRef.value.next();
}

const prePage = () => { 
  swipeRef.value.prev();
}

/**
 * 展开所有题序号，点击并跳转对应题目
 */
const show = ref(false);
const toPage = (index) => {
  show.value = false;
  swipeRef.value.swipeTo(index);
}
</script>

<template>
  <div class="btn-box">
    <p style="flex: 1;">倒计时：<van-count-down ref="countDown" millisecond :time="time"
        format="HH:mm:ss" @finish="onFinish" /></p>
    <p style="margin-right: 1rem;">{{ num }}/{{ listData.length }}</p>
    <van-button type="primary" size="small" @click="examSubmit">交卷</van-button>
  </div>
  <van-skeleton title :row="6" :loading="loading">
    <van-swipe ref="swipeRef" lazy-render :show-indicators=false @change="onChange">
      <van-swipe-item v-for="(item,index) in listData" :key="index">
        <div style="padding:0 1rem;">
          <!-- 选项列表 -->
          <div class="que-one">
            <p><van-tag :color="item.questionType === '0' ? '#67C23A' : '#E6A23C'">{{ typeMap[item.questionType]
                }}</van-tag>&nbsp; {{ index + 1 }}、{{ item.questionContent }}</p>
            <ul>
              <template v-if="item.questionType === '1'">
                <li v-for="(item2, i) in item.answerOptions" :key="i"
                  @click="selectMultiItem($event, item, item2, index, i)">
                  <span>{{ item2.label }}</span>
                </li>
              </template>
              <template v-else>
                <li v-for="(item2, i) in item.answerOptions" :key="i"
                  @click="selectOneItem($event, item, item2, index, i)">
                  <span>{{ item2.label }}</span>
                </li>
              </template>
            </ul>
          </div>
        </div>
      </van-swipe-item>
    </van-swipe>
    <div class="flexbox">
      <van-button plain type="success" size="small" @click="prePage" v-if="num !== 1">上一题</van-button>
      <van-button plain type="success" size="small" @click="nextPage" v-if="num !== listData.length">下一题</van-button>
    </div>
  </van-skeleton>
  <!-- 浮标 -->
  <van-floating-bubble icon="apps-o" @click="show=true" />
  <van-action-sheet v-model:show="show" title="考题序号">
    <div class="small-sybol">
      <p><span class="noanswer"></span>未答</p>
      <p><span class="answered"></span>已答</p>
    </div>
    <ul class="examIndexs">
      <template v-for="(item, index) in listData" :key="index">
        <li v-if="item.isAnswered===1" class="active" @click="toPage(index)">{{ index + 1 }}</li>
        <li v-else @click="toPage(index)">{{ index + 1 }}</li>
      </template>
    </ul>
  </van-action-sheet>
</template>

<style lang="scss" scoped>
.btn-box{
  padding: .5rem;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.van-swipe{
  width: 100%;
  height: auto;
  img{
    width: 100%;
  }
}
.que-one{
  ul {
    padding: 1rem;
    color: #58727e;
    li {
      padding: .5rem;
      margin-bottom: .5rem;
      background-color: #FAFCFF;
      border-radius: 6px;
      transition: all .3s;
      &.active{
        background-color: #C0C4CC;
        color: #fff;
      }
    }
  }
}
.flexbox{
  padding: .5rem 1rem;
  display: flex;
  justify-content: flex-end;
  button{
    margin-left: .5rem;
  }
}
.small-sybol{
  display: flex;
  flex-direction: row;
  padding: 0 1rem;
  align-items: center;
  justify-content: center;
  p{
    display: flex;
    align-items: center;
    padding: 0 .5rem;
    span{
      display: inline-block;
      width: 1rem;
      height: 1rem;
      border-radius: 2px;
      border: 1px solid;
      margin-right: .5rem;
      &.noanswer{
        border-color: #C0C4CC;
        background-color: #fff;
      }
      &.answered{
        background-color: #C0C4CC;
        border-color: #C0C4CC;
      }
    }
  }
}
.examIndexs{
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  padding: 1rem;
  li{
    display: block;
    width: 3rem;
    height: 3rem;
    line-height: 3rem;
    text-align: center;
    box-sizing: border-box;
    border: 1px solid #C0C4CC;
    border-radius: 50%;
    margin: .5rem;
    transition: all .3s;
    &.active{
      background-color: #C0C4CC;
      border-color: #C0C4CC;
      color: #fff;
    }
  }
}
</style>